package com.example.exam.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.exam.entity.Base64;
import com.example.exam.entity.DTO.PaperDTO;
import com.example.exam.entity.SimplePaper;
import com.example.exam.entity.Topic;
import com.example.exam.mapper.Base64Mapper;
import com.example.exam.mapper.SimplePaperMapper;
import com.example.exam.utils.AmazeS3Utils;
import com.example.exam.utils.FileUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zhang
 */
@Service
@Log4j2
public class SimplePaperImpl extends ServiceImpl<SimplePaperMapper, SimplePaper> {
    @Autowired
    private QuestionServiceImpl questionService;
    @Autowired
    private AmazeS3Utils amazeS3Utils;
    @Autowired
    private SimplePaperMapper simplePaperMapper;
    @Autowired
    private Base64Mapper base64Mapper;
    public Integer createPaper(PaperDTO paper) {
        List<Topic> list = questionService.getQuestionListById(paper.getQuestionIds());
        List<Topic> newTopicList = paper.getQuestionbank();
        if (newTopicList != null) {
            list.addAll(newTopicList);
            //保存新的试题
            newTopicList.forEach(i -> {
                i.setStatus(Topic.QUESTION_STATUS_HIDDEN);
            });
            questionService.saveBatch(newTopicList);
        }
        try {
            ObjectMapper mapper = new ObjectMapper();
            String fileName = FileUtils.fileNameToUuid(paper.getPaperName() + ".json");
            SimplePaper simplePaper = new SimplePaper();
            String base = FileUtils.isOneFile(list.toString().getBytes(StandardCharsets.UTF_8));
            Base64 base64 = base64Mapper.selectById(base);
            if (base64 == null) {
                base64 = new Base64();
                base64.setBase64(base);
                base64.setFileName(fileName);
                base64Mapper.insert(base64);
                simplePaper.setPath(fileName);
                amazeS3Utils.streamUpload(fileName,
                        new ByteArrayInputStream(mapper.writeValueAsString(list).getBytes(StandardCharsets.UTF_8)));
                log.info("-----------上传文件成功-----------");
            } else {
                simplePaper.setPath(base64.getFileName());
                log.info("-----------文件已存在-----------");
            }
            simplePaper.setName(paper.getPaperName());
            simplePaper.setTime(LocalDateTime.now());
            simplePaper.setCreateId(1);
            simplePaperMapper.insert(simplePaper);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return 1;
    }


    public String getPaperById(Integer id) {
        String fileName = simplePaperMapper.selectById(id).getPath();
        log.info("fileName:{}", fileName);
        InputStream inputStream = amazeS3Utils.download(fileName);
        if (inputStream != null) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                log.info("解析数据成功:{}", stringBuilder);
                return stringBuilder.toString();
            } catch (IOException e) {
                // 处理异常
                return null;
            }
        }
        return null;
    }
}

